<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :title="title"
    width="660px">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="120px">
      <el-form-item :label="$t('Category')" prop="category">

        <el-radio-group v-model="form.category" @change="radioChange">
          <el-radio :label="1">{{ this.$t("ByEqpModel") }}</el-radio>
          <el-radio :label="2">{{ this.$t("ByEqp") }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- <el-form-item :label="$t('equipmentType')" prop="eqpType">
        <el-select v-model="form.eqpType" :style="{'width': '100%'}" @change="getEqpList">
          <el-option
            v-for="item in eqpTypesList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item
        v-show="form.category === 1"
        :label="$t('nodeLevel')"
        prop="eqpModel">
        <treeselect
          :options="options"
          v-model="form.eqpModel"
          :placeholder="`${$t('pleaseSelect')}${$t('nodeLevel')}`"
          :no-children-text="$t('noMoreData')"
          :no-options-text="$t('noMoreData')"
          :no-results-text="$t('noMoreData')"
        />
      </el-form-item>
      <el-form-item
        v-show="form.category === 2"
        :label="$t('eqpId')"
        prop="eqpId">
        <el-select v-model="form.eqpId" :style="{'width': '100%'}" filterable>
          <el-option
            v-for="item in eqpNameList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('AlarmLevel')" prop="alarmLevel">
        <el-select v-model="form.alarmLevel" :style="{'width': '100%'}">
          <el-option
            v-for="item in levelList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('AlarmCode')" prop="alarmId">
            <el-input v-model="form.alarmId" maxlength="30" show-word-limit/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            :label="$t('HoldCode')"
            prop="holdCode"
          >
            <el-input v-if="boxType === 1" v-model="form.holdCode"/>
            <el-select v-if="boxType === 2" v-model="form.holdCode" :style="{'width': '100%'}">
              <el-option
                v-for="item in holdCodeList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('repeatCount')" prop="repeatCount">
            <el-input
              v-model="form.repeatCount"
              clearable
              onkeyup="this.value = this.value.replace(/[^0-9]/g, '')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('effectiveTime')" prop="effectiveTime">
            <el-input
              v-model="form.effectiveTime"
              clearable
              onkeyup="this.value = this.value.replace(/[^0-9]/g, '')"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item :label="$t('description')" prop="description">
        <el-input v-model="form.description" :rows="5" type="textarea" maxlength="200" show-word-limit/>
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button
        icon="el-icon-circle-close"
        @click="handleClose"
      >{{ $t("cancel") }}</el-button
      >
      <el-button
        v-btnThrottle="doSave"
        type="primary"
        icon="el-icon-receiving"
      >{{ $t("save") }}</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
import {
  getEqpModelList,
  eqptypelist,
  getEqpNameList
} from '@/api/equipment/eqpbase'
import { getAllLevel } from '@/api/alarm/level'
import alarmSetUpApi, { getHoldCodelList } from '@/api/alarm/setup'
import { betterTips } from '@/utils/notification'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getTreeList } from '@/api/equipment/prodTreeNode'

export default {
  name: 'AlarmSetupForm',
  components: { Treeselect },
  data() {
    const validRepeatCount = (rule, value, callback) => {
      if (value > 999 || value < 1) {
        callback(new Error('取值范围: 1-999'))
      } else {
        callback()
      }
    }

    // const validEffectiveTime = (rule, value, callback) => {
    //   if (value < 0) {
    //     callback(new Error(`${this.$t('pleaseInput')}${this.$t('effectiveTime')}`))
    //   } else {
    //     callback()
    //   }
    // }

    return {
      dialogVisible: false,
      title: '',
      form: {
        category: 1,
        eqpType: '',
        eqpId: '',
        eqpModel: undefined,
        repeatCount: 1,
        effectiveTime: 0
      },
      options: [],
      boxType: 1,
      holdCodeList: [],
      eqpTypesList: [],
      eqpModelList: [],
      eqpNameList: [],
      levelList: [],
      rules: {
        category: [
          {
            required: true,
            message: this.$t('CategoryIsRequired'),
            trigger: 'change'
          }
        ],
        eqpModel: [
          {
            required: false,
            message: this.$t('EqpModelIsRequired'),
            trigger: 'change'
          }
        ],
        eqpId: [
          {
            required: false,
            message: this.$t('EqpIsRequired'),
            trigger: 'change'
          }
        ],
        eqpType: [
          {
            required: true,
            message: this.$t('EqpTypeIsRequired'),
            trigger: 'change'
          }
        ],
        alarmLevel: [
          {
            required: true,
            message: this.$t('30005'),
            trigger: 'change'
          }
        ],
        alarmId: [
          {
            required: true,
            message: this.$t('AlarmCodeIsRequired'),
            trigger: 'blur'
          }
        ],
        repeatCount: [{ validator: validRepeatCount, trigger: 'blur' }]
        // effectiveTime: [{ validator: validEffectiveTime, trigger: 'blur' }]
        // holdCode: [
        //   {
        //     required: true,
        //     message: `${this.$t('pleaseInput')}${this.$t('holdCode')}`,
        //     trigger: 'blur'
        //   }
        // ]
      }
    }
  },
  methods: {
    doSave() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.id) {
            alarmSetUpApi.doUpdate({ ...this.form, effectiveTime: this.form.effectiveTime ? this.form.effectiveTime : 0 }).then((res) => {
              betterTips(res, this.handleClose, this.handleUpdate)
            })
          } else {
            alarmSetUpApi.newAdd({ ...this.form, effectiveTime: this.form.effectiveTime ? this.form.effectiveTime : 0 }).then((res) => {
              betterTips(res, this.handleClose, this.handleUpdate)
            })
          }
        } else {
          return false
        }
      })
    },
    radioChange(value) {
      if (this.form.id) return
      switch (value) {
        case 1:
          this.form.eqpId = ''
          // this.eqpNameList = []
          break
        case 2:
          this.form.eqpModel = undefined
          // this.eqpModelList = []
          break
        default:
          break
      }
      this.form.eqpType = ''
    },
    // getEqpList(value) {
    //   switch (this.form.category) {
    //     case 1:
    //       getEqpModelList({ eqptype: value }).then((res) => {
    //         this.eqpModelList = res.data
    //         this.form.eqpModel = undefined
    //       })
    //       break
    //     case 2:
    //       getEqpNameListBy({ EqpType: value }).then((res) => {
    //         this.eqpNameList = res.data
    //         this.form.eqpId = ''
    //       })
    //       break
    //     default:
    //       break
    //   }
    // },
    async handleOpen(row) {
      if (row && row.id) {
        this.title = this.$t('modify')
        const res = await alarmSetUpApi.getInfo({ id: row.id })
        this.form = Object.assign({}, res.data, { eqpModel: res.data.eqpModel ? res.data.eqpModel : undefined })
        this.form.id = row.id
        // if (this.form.category && this.form.eqpType) {
        //   switch (this.form.category) {
        //     case 1:
        //       this.getEqpModelList(this.form.eqpType)
        //       break
        //     case 2:
        //       this.getEqpNameList(this.form.eqpType)
        //       break
        //     default:
        //       break
        //   }
        // }
      } else {
        // do somethings
        this.title = this.$t('add')
      }
      const data = await getTreeList({ check: 1 })
      const formatTree = (root) => {
        return (root || []).map(node => {
          const { id, name, children } = node
          return {
            id,
            label: name,
            children: formatTree(children)
          }
        })
      }
      this.options = formatTree(data.data)
      this.getEqpTypesList()
      this.getAllLevelList()
      this.getEqpNames()
      getHoldCodelList().then(res => {
        if (res.code === 1) {
          this.boxType = res.data.boxType
          this.holdCodeList = Array.isArray(res.data.holdCodelList) ? res.data.holdCodelList : []
        }
      })
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    handleClose() {
      Object.assign(this.$data, this.$options.data.call(this))
    },
    // 触发父组件更新
    handleUpdate() {
      this.$emit('initList')
    },
    async getEqpModelList(value) {
      const res = await getEqpModelList({ eqptype: value })
      this.eqpModelList = res.data
    },
    async getEqpTypesList() {
      const res = await eqptypelist()
      this.eqpTypesList = res.data
    },
    async getEqpNames() {
      const res = await getEqpNameList()
      this.eqpNameList = res.data
    },
    async getAllLevelList() {
      const res = await getAllLevel()
      this.levelList = res.data
    }
    // async getselectitemlist() {
    //   const res = await selectitemlist({ name: 'AMS_DefaultHoldCode' })
    //   if (Array.isArray(res.data) && res.data.length) {
    //     this.$set(this.form, 'holdCode', res.data[0].name)
    //   }
    // }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .vue-treeselect__input-container{
  display: flex;
  align-items: center;
}
</style>
